<template>
  <div class="json-editor-container">
    <el-input v-model="jsonString" :placeholder="placeholder" :rows="8" type="textarea" @blur="validateJson" @input="handleInput" />
    <div v-if="error" class="error-message">{{ error }}</div>
  </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

const props = defineProps<{
  modelValue: any
  placeholder?: string
}>()

const emit = defineEmits(['update:modelValue', 'change'])

const error = ref('')
const jsonString = ref('')

// 初始化和监听值变化
watch(
  () => props.modelValue,
  (newVal) => {
    if (newVal !== undefined) {
      try {
        jsonString.value = JSON.stringify(newVal, null, 2)
        error.value = ''
      } catch {
        error.value = '无效的 JSON 格式'
      }
    }
  },
  { immediate: true }
)

// 处理输入
const handleInput = (value: string) => {
  jsonString.value = value
  validateJson()
}

// 验证 JSON
const validateJson = () => {
  try {
    if (!jsonString.value) {
      emit('update:modelValue')
      error.value = ''
      return
    }
    const parsed = JSON.parse(jsonString.value)
    emit('update:modelValue', parsed)
    error.value = ''
  } catch {
    error.value = '无效的 JSON 格式'
  }
}
</script>

<script lang="ts">
export default {
  name: 'JsonEditor',
}
</script>

<style scoped>
.json-editor-container {
  width: 100%;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
}

:deep(.el-textarea__inner) {
  font-family: monospace;
}
</style>
